package thread.preempt;
import static java.lang.System.out;

/**
 * 
 * @author Shahid
 * 
 */
public class PingPong extends Thread {

	String word;

	public PingPong(String w) {
		word = w;
	}

	@Override
	public void run() {
			for (int count = 1; count <= 10; count++) {
				out.printf("%s%d\t",word,count);
		 // yields control to another thread every 5 iterations
	            if ((count % 5) == 0) {
	               out.println("Yielding...");
	               
       /* causes the currently executing thread object to
        *  temporarily pause and allow other threads to execute */
	               Thread.yield();												
	            }
			}
			out.println("(" + word + ") has finished executing.");
	}

	public static void main(String[] args) {
		out.println("Ping Pong Yield demo");
		
		Thread t1 = new PingPong("Ping");
		Thread t2 = new PingPong("Pong");
		t1.start();
		t2.start();
	}
}

/*Ping Pong Yield demo
Pong1	Pong2	Pong3	Pong4	Pong5	Ping1	Ping2	Ping3	Pong is Yielding
Ping4	Pong6	Pong7	Ping5	Pong8	Ping is Yielding
Pong9	Ping6	Pong10	Ping7	Pong is Yielding
Ping8	Pong has finished executing.
Ping9	Ping10	Ping is Yielding
Ping has finished executing.	*/
